import axios from 'axios'
import { getRedirectPath } from '../util'

const REGISTER_SUCCESS = 'REGISTER_SUCCESS'
const LOGIN_SUCCESS = 'LOGIN_SUCCESS'
const AUTH_SUCCESS = 'AUTH_SUCCESS'
const ERR_MSG = 'ERR_MSG'
const LODA_DATA = 'LODA_DATA'
const LOGOUT = 'LOGOUT'

const initState = {
	redirectTo: '',
	msg: '',
	user: '',
	type: '',
	_id: ''
}

//reducer
export function user(state = initState, action) {
	switch (action.type) {
		case AUTH_SUCCESS:
			return { ...state, msg: '', redirectTo: getRedirectPath(action.payload), ...action.payload }
		case LODA_DATA:
			return { ...state, ...action.payload }
		case ERR_MSG:
			return { ...state, isAuth: false, msg: action.msg }
		case LOGOUT:
			return { ...initState, redirectTo: '/login' }
		default:
			return state
	}
}

function errMsg(msg) {
	return { msg, type: ERR_MSG }
}

function authSuccess(data) {
	return { type: AUTH_SUCCESS, payload: data }
}

export function logoutSubmit() {
	return { type: LOGOUT }
}

export function loadData(userinfo) {
	return { type: LODA_DATA, payload: userinfo }
}

export function update(data) {
	return dispatch => {
		axios.post('/user/update', data)
			.then(res => {
				if (res.status == 200 && res.data.code == 0) {
					dispatch(authSuccess(res.data.data))
				} else {
					dispatch(errMsg(res.data.msg))
				}
			})
	}
}

export function login({ user, pwd }) {
	if (!user || !pwd) {
		return errMsg('用户名和密码必须输入')
	}
	return dispatch => {
		axios.post('/user/login', { user, pwd })
			.then(res => {
				if (res.status == 200 && res.data.code == 0) {
					dispatch(authSuccess(res.data.data))
				} else {
					dispatch(errMsg(res.data.msg))
				}
			})
	}
}

export function register(userState) {
	const { user, pwd, type } = userState
	if (!user || !pwd || !type) {
		return errMsg('用户名和密码必须输入')
	}
	if (userState.pwd !== userState.repwd) {
		return errMsg('密码和确认密码不符')
	}
	return dispatch => {
		axios.post('/user/register', { user, pwd, type })
			.then(res => {
				if (res.status === 200 && res.data.code === 0) {
					dispatch(authSuccess({ user, pwd, type }))
				} else {
					dispatch(errMsg(res.data.msg))
				}
			})
	}
}